package com.shop.cereshop.app.param.buyer;


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

@Data
@ApiModel(value = "UserManageParam", description = "设置用户禁言时长")
public class UserManageParam {
    @ApiModelProperty(value = "禁言账号")
    public String account;

    @ApiModelProperty(value = "用户禁言时长，单位秒")
    public Long c2CmsgNospeakingTime;

    @ApiModelProperty(value = "用户组禁言时长，单位秒")
    public Long groupmsgNospeakingTime;

    @ApiModelProperty(value = "是否禁言,1-是,0否")
    public Integer stopSpeeckType;

    @ApiModelProperty(value = "群聊禁言时长(完整的时间)")
    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
    @JsonDeserialize(using = com.shop.cereshop.admin.param.buyer.UserManageParam.SafeLocalDateTimeDeserializer.class)
    public LocalDateTime groupmsgNospeakingTimeYMD;

    @ApiModelProperty(value = "单聊禁言时长(完整的时间)")
    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
    @JsonDeserialize(using = com.shop.cereshop.admin.param.buyer.UserManageParam.SafeLocalDateTimeDeserializer.class)
    public LocalDateTime c2CmsgNospeakingTimeYMD;

    // 添加获取时间戳的方法，处理 null 情况
    public Long getGroupmsgNospeakingTimeYMD() {
        return groupmsgNospeakingTimeYMD != null ?
                groupmsgNospeakingTimeYMD.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() : 0;
    }

    public Long getC2CmsgNospeakingTimeYMD() {
        return c2CmsgNospeakingTimeYMD != null ?
                c2CmsgNospeakingTimeYMD.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() : 0;
    }

    // 安全的 LocalDateTime 反序列化器
    public static class SafeLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String text = p.getText();

            // 处理 null、空字符串或 "null" 字符串
            if (text == null || text.isEmpty() || "null".equalsIgnoreCase(text)) {
                return null;
            }

            try {
                return LocalDateTime.parse(text, FORMATTER);
            } catch (DateTimeParseException e) {
                // 解析失败时返回 null 而不是抛出异常
                return null;
            }
        }
    }
}